<template>
  <view class="setPassword_outer">
    <view class="record_header">
      <u-navbar :autoBack="true" height="152rpx" bgColor="#FFFAEF" :fixed="true" :border="true" :placeholder="true">
        <view slot="left" class="record_header_back">
          <image src="@/static/record/goback.png"></image>
        </view>
        <view slot="center" class="record_header_title" v-if="pagename == 'login'">设置登录密码</view>
        <view slot="center" class="record_header_title" v-if="pagename == 'pay'">设置支付密码</view>
      </u-navbar>
    </view>
    <view class="setPassword_form">
      <view class="type_box">
        <view class="type_item" :class="{ active: changeType == 0 }" @tap="changeType = 0">使用验证码</view>
        <view class="type_item" :class="{ active: changeType == 1 }" @tap="changeType = 1">使用密钥</view>
      </view>
      <u--form labelPosition="left" ref="uForm">
        <u-form-item ref="item1">
          <view class="setPassword_form_item" style="display: flex; justify-content: space-between">
            <view class="setPassword_form_item_ipt"><u--input v-if="pagename == 'pay'" border="none" placeholder="输入新密码"
                v-model="setPasswordSendData.password" :type="isShowPassword ? 'number' : 'password'">
              </u--input>
              <u--input v-else border="none" placeholder="输入新密码" v-model="setPasswordSendData.password"
                :type="isShowPassword ? 'text' : 'password'">
              </u--input>
            </view>
            <view @click="isShowPassword = !isShowPassword" style="margin-right: 20rpx">
              <u-icon name="eye-fill" v-if="isShowPassword"></u-icon>
              <u-icon name="eye-off" v-else></u-icon>
            </view>
          </view>
        </u-form-item>
        <u-form-item ref="item2">
          <view class="setPassword_form_item" style="display: flex; justify-content: space-between">
            <view class="setPassword_form_item_ipt"><u--input v-if="pagename == 'pay'" border="none" placeholder="再次输入新密码"
                v-model="setPasswordSendData.confirmPassword" :type="isShowPassword2 ? 'number' : 'password'">
              </u--input>
              <u--input v-else border="none" placeholder="再次输入新密码" v-model="setPasswordSendData.confirmPassword"
                :type="isShowPassword2 ? 'text' : 'password'">
              </u--input>
            </view>
            <view @click="isShowPassword2 = !isShowPassword2" style="margin-right: 20rpx">
              <u-icon name="eye-fill" v-if="isShowPassword2"></u-icon>
              <u-icon name="eye-off" v-else></u-icon>
            </view>
          </view>
        </u-form-item>
        <u-form-item ref="item3">
          <view class="login_content_verification" v-if="changeType == 0">
            <view class="login_content_verification_ipu">
              <u--input border="none" placeholder="手机验证码" v-model="setPasswordSendData.code">
              </u--input>
            </view>
            <view class="login_content_verification_uToast">
              <u-toast ref="uToast"></u-toast>
              <u-code :seconds="seconds" startText="获取" changeText="x秒" ref="uCode" @end="end" @start="start"
                @change="codeChange"></u-code>
              <view class="login_content_verification_uToast_btn" @click="getCanvasVerification">{{ tips }}</view>
            </view>
          </view>
          <view class="login_content_superPassword" v-if="changeType == 1">
            <view class="login_content_superPassword_ipu">
              <u--input border="none" placeholder="输入密钥" v-model="setPasswordSendData.validCdoe">
              </u--input>
            </view>
          </view>
        </u-form-item>
        <u-form-item ref="item4">
          <view class="setPassword_affirm">
            <view class="setPassword_affirm_btn" @click="getSetPassword">
              <text>确定更改</text>
            </view>
          </view>
        </u-form-item>
      </u--form>
    </view>
    <view style="position: relative; z-index: 99">
      <u-popup :show="isShowVerificationImgUrl" mode="center" round="30" :closeOnClickOverlay="true"
        @close="isShowVerificationImgUrl = false">
        <view class="verification_box">
          <view class="verificationImg" @click="getCanvasVerification">
            <image :src="verificationImgUrl.encode"></image>
          </view>
          <view class="verificationIpt">
            <view>
              <u--input border="none" placeholder="请输入图形验证码" v-model="sendVerificationCode">
              </u--input>
            </view>
          </view>
          <view class="verificationIpt_affirm">
            <view @click="reqSendNoteCode">
              <text>确定</text>
            </view>
          </view>
        </view>
      </u-popup>
    </view>
    <u-notify ref="uNotify" message="Hi uView"></u-notify>
  </view>
</template>

<script>
import { reqSetPayPassword, reqSetLoginPassword, reqSetPasswordByValidCode, reqSetPayPasswordByValidCode } from "@/api/setPassword.js";
import { reqCanvasVerification, reqSendNoteCode } from "@/api/all.js";

export default {
  data() {
    return {
      tips: "",
      seconds: 60,
      pagename: "",
      // 人机验证码
      verificationImgUrl: {},
      // 是否展示人机验证码
      isShowVerificationImgUrl: false,
      // 人机验证码
      sendVerificationCode: "",
      // 是否能发送验证码
      isSendVerificationCode: true,
      // 设置支付密码参数
      setPasswordSendData: {
        password: "",
        confirmPassword: "",
        code: "",
        validCdoe: ''
      },
      isShowPassword: false,
      isShowPassword2: false,
      changeType: 0 //0 -- 验证码 ， 1 -- 密钥
    };
  },
  onLoad(option) {
    this.pagename = option.pagename;
  },
  methods: {
    //获取人机校验码
    getCanvasVerification: _.throttle(async function () {
      if (!this.isSendVerificationCode) return;
      const result = await reqCanvasVerification();
      if (result.code == 200) {
        this.verificationImgUrl = result.data;
        this.isShowVerificationImgUrl = true;
      } else {
        uni.showToast({
          title: result.msg,
          icon: "error",
        });
      }
    }, 2000),
    //发送短信
    async reqSendNoteCode() {
      if (!this.sendVerificationCode) {
        uni.showToast({
          title: "请输入图形验证码",
          icon: "error",
        });
      } else {
        let sendData;
        switch (this.pagename) {
          case "pay":
            sendData = {
              phone: uni.getStorageSync("phone"),
              captchaId: this.verificationImgUrl.id,
              captcha: this.sendVerificationCode,
              scenes: 3,
            };
            break;
          case "login":
            sendData = {
              phone: uni.getStorageSync("phone"),
              captchaId: this.verificationImgUrl.id,
              captcha: this.sendVerificationCode,
              scenes: 4,
            };
            break;
        }
        const result = await reqSendNoteCode(sendData);
        if (result.code == 200) {
          this.$refs.uNotify.show({
            top: 10,
            type: "success",
            color: "white",
            bgColor: "#FF9E3C",
            message: "短信验证码发送成功",
            duration: 1000 * 3,
            fontSize: 20,
            safeAreaInsetTop: true,
          });
          this.getCode();
          this.isShowVerificationImgUrl = false;
        } else {
          // this.$refs.uNotify.show({
          //   top: 10,
          //   type: "error",
          //   color: "white",
          //   bgColor: "red",
          //   message: result.msg,
          //   duration: 1000 * 3,
          //   fontSize: 20,
          //   safeAreaInsetTop: true,
          // });
          uni.$u.toast(result.msg);
          this.getCanvasVerification();
        }
      }
    },
    codeChange(text) {
      this.tips = text;
    },
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: "正在获取验证码",
        });
        setTimeout(() => {
          uni.hideLoading();
          // 这里此提示会被this.start()方法中的提示覆盖
          uni.$u.toast("验证码已发送");
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start();
        }, 2000);
      } else {
        uni.$u.toast("倒计时结束后再发送");
      }
    },
    start() {
      this.isSendVerificationCode = false;
    },
    end() {
      this.isSendVerificationCode = true;
    },

    // 判断设置密码
    getSetPassword: _.throttle(async function () {
      console.log(isNaN(this.setPasswordSendData.password));

      const that = this;
      let isSend = false;
      let hignArr = ["新密码", "确认新密码"];
      let hignIndex = 0;
      let newobj = {
        password: this.setPasswordSendData.password,
        confirmPassword: this.setPasswordSendData.confirmPassword
      }
      if(this.changeType == 0) {
        hignArr.push("短信验证码");
        newobj['code'] = this.setPasswordSendData.code;
      }
      if(this.changeType == 1){
        hignArr.push("密钥");
        newobj['validCdoe'] = this.setPasswordSendData.validCdoe;
      } 

      for (let key in newobj) {
        if (!newobj[key]) {
          isSend = false;
          break;
        } else {
          isSend = true;
        }
        hignIndex++;
      }
      if (
        this.setPasswordSendData.password !=
        this.setPasswordSendData.confirmPassword
      ) {
        uni.showToast({
          title: "两次密码不一致",
          icon: "error",
        });
        isSend = false;
        return;
      }

      if (isSend) {
        switch (this.pagename) {
          case "pay":
            that.getSetPayPassword();
            break;
          case "login":
            that.getSetLoginPassword();
            break;
        }
      } else {
        uni.showToast({
          title: `${hignArr[hignIndex]}不能为空`,
          icon: "error",
        });
      }
    }),
    // 设置支付密码
    async getSetPayPassword() {
      if (
        isNaN(this.setPasswordSendData.password) ||
        this.setPasswordSendData.password.length != 6
      ) {
        uni.showToast({
          title: "支付密码格式为6位纯数字",
          icon: "error",
        });
        return;
      }
      if (this.changeType == 0) {
        const sendData = {
          code: this.setPasswordSendData.code,
          payPassword: this.setPasswordSendData.password,
          confirmPassword: this.setPasswordSendData.confirmPassword,
        };
        const result = await reqSetPayPassword(sendData);
        if (result.code == 200) {
          uni.showLoading({
            title: "修改成功",
          });
          let userInfo = { ...uni.getStorageSync('userInfo'), setPayPwd: 1 }
          uni.setStorageSync('userInfo', userInfo)
          setTimeout(() => {
            uni.hideLoading();
            //在起始页面跳转到test.vue页面并传递参数
            uni.switchTab({
              url: "/pages/my/index",
            });
          }, 1000);
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });
        }
      } else {
        const sendData = {
          validCdoe: this.setPasswordSendData.validCdoe,
          payPassword: this.setPasswordSendData.password,
          confirmPassword: this.setPasswordSendData.confirmPassword,
        };
        const result = await reqSetPayPasswordByValidCode(sendData);
        if (result.code == 200) {
          uni.showLoading({
            title: "修改成功",
          });
          let userInfo = { ...uni.getStorageSync('userInfo'), setPayPwd: 1 }
          uni.setStorageSync('userInfo', userInfo)
          setTimeout(() => {
            uni.hideLoading();
            //在起始页面跳转到test.vue页面并传递参数
            uni.switchTab({
              url: "/pages/my/index",
            });
          }, 1000);
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });
        }
      }
    },
    // 设置登录密码
    async getSetLoginPassword() {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,20}$/;
      if (!reg.test(this.setPasswordSendData.password)) {
        uni.showToast({
          title: "密码格式为6-20位数字加字母",
          icon: "error",
        });
        return;
      }
      if (this.changeType == 0) {
        const sendData = {
          code: this.setPasswordSendData.code,
          password: this.setPasswordSendData.password,
          confirmPassword: this.setPasswordSendData.confirmPassword,
        };
        const result = await reqSetLoginPassword(sendData);
        if (result.code == 200) {
          this.loginOut()
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });
        }
      } else {
        const sendData = {
          validCdoe: this.setPasswordSendData.validCdoe,
          password: this.setPasswordSendData.password,
          confirmPassword: this.setPasswordSendData.confirmPassword,
        };
        const result = await reqSetPasswordByValidCode(sendData);
        if (result.code == 200) {
          this.loginOut()
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });
        }
      }
    },
    // 退出登录
    loginOut() {
      uni.showLoading({
        title: "修改成功，请重新登陆",
      });
      setTimeout(() => {
        uni.hideLoading()
        uni.removeStorageSync("userInfo");
        uni.removeStorageSync("phone");
        uni.removeStorageSync("onlyCode");
        window.history.replaceState(null, null, '/')
        uni.navigateTo({
          url: "/pages/information/index",
        });
      }, 2000);
    },
  },
};
</script>

<style lang="scss" scoped>
.setPassword_outer {
  width: 100vw;
  height: 100vh;
  background: #fffaef;

  .record_header {
    .record_header_title {
      font-size: 46rpx;
      font-family: DreamHanSansSC;
      font-weight: 600;
      color: #302b26;
    }

    .record_header_back {
      width: 46rpx;
      height: 46rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .setPassword_form {
    display: flex;
    flex-direction: column;
    align-items: center;
    border-top: 2rpx solid rgba(183, 178, 169, 0.35);
    padding-top: 90rpx;

    .type_box {
      width: 100%;
      padding: 0 0 32rpx 96rpx;
      display: flex;
      align-items: center;

      .type_item {
        font-size: 36rpx;
        color: #333;
        margin-right: 32rpx;

        &.active {
          font-size: 40rpx;
          font-weight: 600;
        }
      }
    }

    .setPassword_form_item {
      width: 663rpx;
      height: 74rpx;
      border: 3px solid #ff9e3c;
      border-radius: 26rpx;
      display: flex;
      align-items: center;

      .setPassword_form_item_ipt {
        margin-left: 46rpx;
        width: 600rpx;
      }
    }

    .login_content_verification {
      width: 663rpx;
      height: 74rpx;
      display: flex;
      align-items: center;

      .login_content_verification_ipu {
        width: 504rpx;
        height: 74rpx;
        border: 3px solid #ff9e3c;
        border-radius: 26rpx;
        display: flex;
        align-items: center;
        padding-left: 46rpx;
      }

      .login_content_verification_uToast {
        width: 142rpx;
        height: 74rpx;
        background: #2f2a26;
        background: linear-gradient(to right, #666157 0%, #504c43 100%);
        border-radius: 26rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 12rpx;

        .login_content_verification_uToast_btn {
          font-size: 31rpx;
          font-family: DreamHanSansSC;
          font-weight: normal;
          color: #fffaef;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }

    .login_content_superPassword {
      width: 663rpx;
      height: 74rpx;
      display: flex;
      align-items: center;

      .login_content_superPassword_ipu {
        width: 663rpx;
        height: 74rpx;
        border: 3px solid #ff9e3c;
        border-radius: 26rpx;
        display: flex;
        align-items: center;
        padding-left: 46rpx;
      }
    }

    .setPassword_affirm {
      display: flex;
      justify-content: center;
      position: fixed;
      bottom: 10%;

      .setPassword_affirm_btn {
        width: 663rpx;
        height: 108rpx;
        background: #ff7006;
        border-radius: 38rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        text {
          font-size: 38rpx;
          font-family: DreamHanSansSC;
          font-weight: 800;
          color: #ffffff;
        }
      }
    }
  }

  .verification_box {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 600rpx;
    height: 600rpx;

    .verificationIpt {
      width: 400rpx;
      height: 100rpx;
      border: 4rpx solid orange;
      border-radius: 38rpx;
      margin-top: 30rpx;
      display: flex;
      align-items: center;

      view {
        margin-left: 30rpx;
      }
    }

    .verificationImg {
      width: 400rpx;
      height: 200rpx;
      margin-top: 40rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .verificationIpt_affirm {
      display: flex;
      justify-content: center;
      margin-top: 30rpx;

      view {
        width: 400rpx;
        height: 108rpx;
        background: linear-gradient(to right, #ff7007 0%, #ffa749 100%);
        border-radius: 38rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        text {
          font-size: 38rpx;
          font-family: DreamHanSansSC;
          font-weight: normal;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
